package app.beit.fintrack.controller.summarytrack;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import app.beit.fintrack.bean.HospitalBean;
import app.beit.fintrack.bean.NavigationBean;
import app.beit.fintrack.bean.summary.SummaryTrackByStatusBean;
import app.beit.fintrack.bean.summary.SummaryTrackDetailsDataBean;
import app.beit.fintrack.controller.BaseController;
import app.beit.fintrack.controller.ResponseFintrack;
import app.beit.fintrack.controller.bean.SummaryTrackSessionBean;
import app.beit.fintrack.controller.bean.pages.SummaryTrackPageDetailsData;
import app.beit.fintrack.service.summarytrack.SummaryTrackService;
import app.beit.fintrack.utils.DateFormatUtils;
import app.beit.fintrack.utils.constr.SessionConstr;
import app.beit.fintrack.utils.enums.ESearchBy;
import app.beit.fintrack.utils.enums.ESearchByStatus;

@Controller
@RequestMapping("/summary/details/data")
public class SummaryTrackDetailsDataController extends BaseController {
	
	private final Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private SummaryTrackService summaryTrackService;
	
	@SuppressWarnings("unchecked")
	@RequestMapping(method=RequestMethod.GET)
	public String execute(final HttpServletRequest request, @RequestParam("repNo") String repNo, @RequestParam("status") String status){
		final SummaryTrackSessionBean stsb = (SummaryTrackSessionBean) super.getAttributeInSession(request, SessionConstr.SESSION_SUMMARY);
		this.log.info("summary details data pid from repno : " + repNo);
		List<NavigationBean> navis = (List<NavigationBean>) request.getSession().getAttribute(SessionConstr.NAVIGATION);
		final int thisSort = 3;
		if(stsb.getCurrentPage() == thisSort){
			navis = stsb.getNavigations();
		}
		
		System.err.println("#######"+navis.toString());
		boolean isAddNavi = true;
		int removeNavi = 0;
		NavigationBean oldNavi = null;
		for(final NavigationBean navi : navis){
			final int sort = navi.getSort();
			if(sort == thisSort){
				isAddNavi = false;
			}
			if(sort == thisSort-1){
				navi.setUrl(request.getContextPath()+"/summary/details?zoneId="+stsb.getPageRepNo().getZone().getZoneId());
				removeNavi = sort-1;
				oldNavi = navi;
			}
		}
		
		if(isAddNavi){
			navis.remove(removeNavi);
			final NavigationBean bean = new NavigationBean();
			bean.setSort(thisSort);
			bean.setName(repNo);
			bean.setUrl("");
			navis.add(oldNavi);
			navis.add(bean);
		}
		try{
			BigDecimal actAmount = new BigDecimal(0);
			
			final SummaryTrackPageDetailsData detailsData = new SummaryTrackPageDetailsData();
			detailsData.setRepNo(repNo);
			detailsData.setStatus(status);
			detailsData.setHospital(stsb.getPageRepNo().getHospital());
			detailsData.setProvince(stsb.getPageRepNo().getProvince());
			detailsData.setZone(stsb.getPageRepNo().getZone());

			String hCode = "";
			final HospitalBean hospitalBean = stsb.getPageRepNo().getHospital();
			if(hospitalBean != null){
				hCode = hospitalBean.getHospitalCode();
				if(hCode != null && hCode.length() > 0){
					final int len = hCode.length();
					hCode = hCode.substring(len - 5, len);
				}
			}
			
			if(status.equalsIgnoreCase("transfer")){
				final List<SummaryTrackByStatusBean> lstResults = new ArrayList<SummaryTrackByStatusBean>();
				final List<SummaryTrackByStatusBean> lst = this.summaryTrackService.getBatchTransferFromRegup(hCode, repNo);
				if(lst != null){
					for(final SummaryTrackByStatusBean bean : lst){
						final Date runDate = bean.getRunDate();
						bean.setStrRunDate(DateFormatUtils.fullMonthThai(runDate));
						lstResults.add(bean);
						final String expression = bean.getExpression();
						if(expression.equalsIgnoreCase("H")){
							actAmount = actAmount.add(bean.getAmount());
						}else if(expression.equalsIgnoreCase("S")){
							actAmount = actAmount.subtract(bean.getAmount());
						}
					}
				}

				detailsData.setRegupPayableBeans(lstResults);
			}else if(status.equalsIgnoreCase("payable")){
				final List<SummaryTrackByStatusBean> lst = this.summaryTrackService.getBatchTransferFromZIFEbudgetPostDateNotNull(hCode, repNo);
				if(lst != null){
					for(final SummaryTrackByStatusBean bean : lst){
						actAmount = actAmount.add(bean.getAmount());
					}
				}
			}else if(status.equalsIgnoreCase("budget")){
				final List<SummaryTrackByStatusBean> lst = this.summaryTrackService.getBatchTransferFromZIFEbudgetPostDateNull(hCode, repNo);
				if(lst != null){
					for(final SummaryTrackByStatusBean bean : lst){
						actAmount = actAmount.add(bean.getAmount());
					}
				}
			}else{
				detailsData.setRegupPayableBeans(null);
				actAmount = this.summaryTrackService.getSumsActAmount(hCode, repNo, stsb.getFromDate(), stsb.getToDate(), "", "");
			}
			
			detailsData.setAllPersonActAmount(actAmount);
			detailsData.setActAmount(actAmount);
			stsb.setPageDetailsData(detailsData);

			super.setAttributeInSession(request, SessionConstr.SESSION_SUMMARY, stsb);
			super.setAttributeInSession(request, SessionConstr.NAVIGATION, navis);
			this.log.info("end summary details data pid.........");
		}catch (Exception e) {
			this.log.error(e.getMessage());
			e.printStackTrace();
		}
		
		return "summaryTrackStation/summaryTrackStationDetailsData";
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="getListDetails", method=RequestMethod.POST)
	public @ResponseBody ResponseFintrack<SummaryTrackPageDetailsData> getListSummaryTrackDetails(final HttpServletRequest request, @RequestParam("start") final int start, 
			@RequestParam("end") final int end, final @RequestParam("searchBy") String searchBy, @RequestParam("value") String value){
		ResponseFintrack<SummaryTrackPageDetailsData> response = null;
		final SummaryTrackSessionBean stsb = (SummaryTrackSessionBean) super.getAttributeInSession(request, SessionConstr.SESSION_SUMMARY);
		
		List<SummaryTrackDetailsDataBean> results = new ArrayList<SummaryTrackDetailsDataBean>();
		final SummaryTrackPageDetailsData detailsData = stsb.getPageDetailsData();
		try {
			String hCode = "";
			final HospitalBean hospitalBean = stsb.getPageDetailsData().getHospital();
			if(hospitalBean != null){
				hCode = hospitalBean.getHospitalCode();
				if(hCode != null && hCode.length() > 0){
					final int len = hCode.length();
					hCode = hCode.substring(len - 5, len);
				}
			}

			final String repNo = detailsData.getRepNo();
			final Date fromDate = stsb.getFromDate();
			final Date toDate = stsb.getToDate();
			results = this.summaryTrackService.getDetailsByRepNo(hCode, repNo, fromDate, toDate, start, end, searchBy, value);

			BigDecimal allPerson = new BigDecimal(0);
			BigDecimal appeal = new BigDecimal(0);
			BigDecimal notPass = new BigDecimal(0);
			BigDecimal notPassDeny = new BigDecimal(0);
			BigDecimal pass = new BigDecimal(0);
			
			ESearchByStatus ess = null;
			if(ESearchBy.STATUS.getSearchBy().equalsIgnoreCase(searchBy)){
				if(ESearchByStatus.APPEAL.getSearchBy().equalsIgnoreCase(value)){
					ess = ESearchByStatus.APPEAL;
					appeal = this.summaryTrackService.getCountPerson(hCode, repNo, fromDate, toDate, searchBy, value, ESearchByStatus.APPEAL);
				}else if(ESearchByStatus.PASS.getSearchBy().equalsIgnoreCase(value)){
					ess = ESearchByStatus.PASS;
					pass = this.summaryTrackService.getCountPerson(hCode, repNo, fromDate, toDate, searchBy, value, ESearchByStatus.PASS);
				}else if(ESearchByStatus.NOT_PASS.getSearchBy().equalsIgnoreCase(value)){
					ess = ESearchByStatus.NOT_PASS;
					notPass = this.summaryTrackService.getCountPerson(hCode, repNo, fromDate, toDate, searchBy, value, ESearchByStatus.NOT_PASS);
				}else if(ESearchByStatus.NOT_PASS_C.getSearchBy().equalsIgnoreCase(value)){
					ess = ESearchByStatus.NOT_PASS_C;
					notPassDeny = this.summaryTrackService.getCountPerson(hCode, repNo, fromDate, toDate, searchBy, value, ESearchByStatus.NOT_PASS_C);
				}
			}else{
				appeal = this.summaryTrackService.getCountPerson(hCode, repNo, fromDate, toDate, searchBy, value, ESearchByStatus.APPEAL);
				notPass = this.summaryTrackService.getCountPerson(hCode, repNo, fromDate, toDate, searchBy, value, ESearchByStatus.NOT_PASS);
				notPassDeny = this.summaryTrackService.getCountPerson(hCode, repNo, fromDate, toDate, searchBy, value, ESearchByStatus.NOT_PASS_C);
				pass = this.summaryTrackService.getCountPerson(hCode, repNo, fromDate, toDate, searchBy, value, ESearchByStatus.PASS);
			}
			allPerson = this.summaryTrackService.getCountPerson(hCode, repNo, fromDate, toDate, searchBy, value, ess);
			
			BigDecimal actAmount = null;
			if(searchBy != null && searchBy.length() > 0){
				actAmount = this.summaryTrackService.getSumsActAmount(hCode, repNo, fromDate, toDate, searchBy, value);
			}else{
				actAmount = detailsData.getAllPersonActAmount();
			}

			detailsData.setCountAllPerson(allPerson);
			detailsData.setCountAppeal(appeal);
			detailsData.setCountNotPass(notPass);
			detailsData.setCountNotPassDeny(notPassDeny);
			detailsData.setCountPass(pass);
			detailsData.setActAmount(actAmount);
			detailsData.setTotal(this.summaryTrackService.getSumsTotal(hCode, repNo, fromDate, toDate, searchBy, value));
			detailsData.setSearchBy(searchBy);
			detailsData.setValue(value);
			detailsData.setDetailsDataBeans(results);
			stsb.setPageDetailsData(detailsData);
			
			response = super.responseSuccess();
			response.setDatas(detailsData);
			
			stsb.setUrl("/summary/details/data?repNo="+ repNo + "&status=" + stsb.getPageDetailsData().getStatus());
			stsb.setCurrentPage(3);
			
			request.getSession().setAttribute(SessionConstr.SESSION_SUMMARY_TRACK, stsb);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return response;
	}

	@RequestMapping(value="/{repNo}", method=RequestMethod.GET)
	public ModelAndView exportXLS(final HttpServletRequest request, final HttpServletResponse response){
		final SummaryTrackSessionBean stsb = (SummaryTrackSessionBean) super.getAttributeInSession(request, SessionConstr.SESSION_SUMMARY);
		try{
			final Date fd = stsb.getFromDate();
			final Date td = stsb.getToDate();
			String hCode = "";
			final HospitalBean hospitalBean = stsb.getPageDetailsData().getHospital();
			if(hospitalBean != null){
				hCode = hospitalBean.getHospitalCode();
				if(hCode != null && hCode.length() > 0){
					final int len = hCode.length();
					hCode = hCode.substring(len - 5, len);
				}
			}
			final String repNo = stsb.getPageDetailsData().getRepNo();
			final int allPerson = Integer.parseInt(stsb.getPageDetailsData().getCountAllPerson().toString());
			final String searchBy = stsb.getPageDetailsData().getSearchBy();
			final String value = stsb.getPageDetailsData().getValue();
			final List<SummaryTrackDetailsDataBean> lstSummaryDetails = this.summaryTrackService.getDetailsByRepNo(hCode, repNo, fd, td, 0, allPerson, searchBy, value);
			return new ModelAndView("excelView", "listSummaryDetails", lstSummaryDetails);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
